import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Modal, Button, message, Input, Select, InputNumber } from 'antd';
import { Form } from '@ant-design/compatible';
import { transferOption } from "@/support/utils";
import { findDicByCodeSort } from "@/support/common";
import PropTypes from "prop-types";

const FormItem = Form.Item;
@connect()
@Form.create({
    mapPropsToFields(props) {
        const formDataEdit = Object.assign({}, props.formData);
        for (const i in formDataEdit) {
            if(i === "mailPlatform" && formDataEdit[i]){
                formDataEdit[i]=Form.createFormField({value:formDataEdit[i] + ""});
            } else {
                formDataEdit[i]= Form.createFormField({value:formDataEdit[i]});
            }
        }
        return formDataEdit;
    },
})
export default class EmailModal extends PureComponent<any, any> {

    static contextTypes = {
        permissions: PropTypes.array,
        dicData: PropTypes.object,
    };

    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
        };
    }

    handleSubmit = () => {
        const { form: { validateFieldsAndScroll }, dispatch, formData, handleFlush} = this.props;
        validateFieldsAndScroll((err: any, values: any) => {
            if (err) return;
            const data = {...values};
            // 判断属于什么操作   1新增2编辑
            if(formData.mailCd){
                data.flag = 2
            } else {
                data.flag =1
            }
            this.setState({ loading: true});
            dispatch({
                type: 'base/addWithRes',
                payload: { url: "/message/channel/updateEmail", ...data },
                callback: (response: any) => {
                    if(response.statusCode === '0') {
                        message.success( formData.mailCd ? '编辑成功': '新增成功');
                        this.handleClose();
                        handleFlush();
                    } else {
                        message.error(response.statusMessage);
                    }
                    this.setState({ loading: false});
                },
            });
        });
    };

    handleClose = () => {
        const { changeVisible } = this.props;
        const { resetFields } = this.props.form;
        resetFields();
        changeVisible();
    };


    render() {
        const { formData, visible } = this.props;
        const { getFieldDecorator } = this.props.form;
        const { loading } = this.state;
        const messageCenterEmailList = findDicByCodeSort(this.context.dicData,"messageCenterEmail");
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 12 },
                md: { span: 16 },
            },
        };
        return (
            <Modal
                style={{ top: 20 }}
                title={formData.mailCd ? "编辑" : '新增'}
                wrapClassName="wrapModel"
                visible={visible}
                onCancel={() => this.handleClose()}
                footer={[
                    <Button size="small" key="back" type="ghost" onClick={() => this.handleClose()}>
                        取消
                    </Button>,
                    <Button size="small" key="submit" type="primary" loading={loading} onClick={() => this.handleSubmit()}>
                        保存
                    </Button>,
                ]}
            >
                <Form style={{ marginTop: 12 }}>
                    <FormItem
                        {...formItemLayout}
                        label="邮件编号"
                    >
                        {getFieldDecorator('mailCd', {
                            rules: [{ required: true, message: '邮件编码不能为空！'},{message: '邮件编码不能超过100位!',max:100 }]
                        })(
                            <Input disabled={!!formData.mailCd} placeholder="请输入邮件编码" maxLength={50} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="邮件平台"
                    >
                        {getFieldDecorator('mailPlatform', {
                            rules: [{ required: true, message: '邮件平台不能为空！' }],
                        })(
                            <Select
                                allowClear
                                placeholder="请选择邮件平台"
                                getPopupContainer={triggerNode => triggerNode.parentNode}
                            >
                                { transferOption(messageCenterEmailList,["dictKey","dictValue"])}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="邮件平台主机地址"
                    >
                        {getFieldDecorator('mailHost', {
                            rules: [{ required: true, message: '邮件平台地址不能为空！'},{message: '邮件平台地址不能超过150位!',max:150 }],
                        })(
                            <Input placeholder="请输入邮件平台地址"  maxLength={150}/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="邮件平台服务端口"
                    >
                        {getFieldDecorator('mailPort', {
                            rules: [{ required: true, message: '邮件平台服务端口不能为空！' }],
                        })(
                            <InputNumber
                                style={{ width:"100%" }}
                                placeholder="请输入邮件平台服务端口"
                                min={1}
                                max={99999}
                            />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="编码方式"
                    >
                        {getFieldDecorator('mailDefaultEncoding', {
                            rules: [{ required: true, message: '编码方式不能为空！' }],
                        })(
                            <Select
                                allowClear
                                placeholder="请选择编码方式"
                                getPopupContainer={triggerNode => triggerNode.parentNode}
                            >
                                <Option value="UTF-8">UTF-8</Option>
                                <Option value="GB2312">GB2312</Option>
                                <Option value="GB18030">GB18030</Option>
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="邮件登录账号"
                    >
                        {getFieldDecorator('mailUsername', {
                            rules: [{ required: true, message: '邮件登录账号不能为空！' },{message: '邮件登录账号不能超过150位!',max:150 }],
                        })(
                            <Input placeholder="请输入邮件登录账号" maxLength={150}/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="邮件登录密码"
                    >
                        {getFieldDecorator('mailPassword', {
                            rules: [{ required: true, message: '邮件登录密码不能为空！' },{  message: '邮件登录密码不能超过150位!',max:150 }],
                        })(
                            <Input.Password placeholder="请输入邮件登录密码" maxLength={150}/>
                        )}
                    </FormItem>
                </Form>
            </Modal>
        );
    }
}
